//
//  CLDiseaseStyleController.m
//  CareLink
//
//  Created by whong7 on 16/8/19.
//  Copyright © 2016年 Seven Team. All rights reserved.
//

#import "CLDiseaseStyleController.h"
#import "CLDiseaseStyleModel.h"
#import "UTPinYinHelper.h"
//设定cellid
static NSString *cellid = @"diseaseStyle_cell";


@interface CLDiseaseStyleController ()<UITableViewDelegate,UITableViewDataSource>

//tableView
@property(nonatomic,strong)UITableView *tableView;
//searchBar
@property(nonatomic,weak)UITextField *searchBar;

//网络请求管理器
@property(nonatomic,strong)CLNetworkManager *networkManager;
//数据数组
@property(nonatomic,strong)NSArray *dataArray;
//返回的模型
@property(nonatomic,strong)CLDiseaseStyleModel *returnModel;
//病类名数组
@property(nonatomic, strong)NSArray *aryNames;
//搜索出来的数组
@property(nonatomic, strong)NSMutableArray *arySearchedNames;


@end

@implementation CLDiseaseStyleController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadData];
}


-(void)setupUI
{
    //view布局
    self.view.backgroundColor = [UIColor colorWithHex:0xF5F5F5];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    //设置导航控制器标题
    self.navigationItem.title = @"疾病详情选择";
    [self.navigationController.navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName : [UIFont systemFontOfSize:17] }];
    //tableView布局
    [self setupTableView];
    //搜索框布局
    [self setupSearchTextView];
    //初始化
    //滑动的时候自动隐藏键盘
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
#warning mark ---------设置返回按钮文字为空
    // 设置返回的按钮的文字为空
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    
}
//MARK:布局搜索框

- (void)setupSearchTextView
{
    //创建 搜索框
    UITextField *searchBar = [[UITextField alloc] init];
    [searchBar addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];

    // 设置背景图片
    UIImage *image = [UIImage imageNamed:@"searchbar_textfield_background"];
    searchBar.background = [image stretchableImageWithLeftCapWidth:image.size.width / 2 topCapHeight:image.size.height / 2];

    // 设置文字内容垂直居中
    searchBar.contentVerticalAlignment = UIControlContentHorizontalAlignmentCenter;

    // 设置左边的放大镜
    UIImageView *leftView = [[UIImageView alloc] init];
    leftView.frame = CGRectMake(0, 0, 40, 35);
    leftView.image = [UIImage imageNamed:@"searchbar_textfield_search_icon"];
    searchBar.leftView = leftView;
    
    // 设置leftViewMode
    searchBar.leftViewMode = UITextFieldViewModeAlways;
    
    // 设置放大镜距离左边的间距，设置leftView的内容居中
    leftView.contentMode = UIViewContentModeCenter;

    //设置约束
    [self.view addSubview:searchBar];
    [searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(8);
        make.left.offset(8);
        make.right.offset(-8);
        make.height.offset(35);
    }];
    
    self.searchBar = searchBar;
}

//MARK:布局tableView
-(void)setupTableView
{
    //添加tableView
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(43);
        make.left.right.bottom.offset(0);
    }];
    
    __weak typeof(self) weakSelf = self;
    //MARK: 下拉刷新
    tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //请求下拉数据
        //如果病情名数组为空，则不进行添加操作
        if (weakSelf.aryNames.count != 0) {
            [weakSelf.totalDetails setObject:@"2" forKey:@"page"];
        }
        
        [weakSelf loadData];
        
    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    tableView.mj_header.automaticallyChangeAlpha = YES;
    
    //注册单元格
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellid];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //设置背景颜色
    self.tableView.backgroundColor = [UIColor colorWithHex:0xF5F5F5];
    //去掉多余的线
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView setTableFooterView:v];

}

#pragma mark - 加载数据 并给 模型数组 赋值
-(void)loadData
{
    //选择科目内部数据
    NSString *ci1_id = self.totalDetails[@"ci1_id"];
    NSString *page = self.totalDetails[@"page"];
    
    NSString *url = @"http://iosapi.itcast.cn/searchCI3List.json.php";
    NSDictionary *paramDic = @{@"login_token":@"985c96ce43bb5ef69de3e1ad8afaa83f",@"keyword":@"",@"ci1_id":ci1_id,@"page_size":@(15),@"page":page};
    
    [self.networkManager POST:url parameters:paramDic success:^(id responseObject) {
        
        if ([self.totalDetails[@"page"] isEqualToString:@"1"])
        {
            
            NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            
            //得到二级病类的模型数组
            self.dataArray = [NSArray yy_modelArrayWithClass:[CLDiseaseStyleModel class] json:response[@"data"]].copy;
            NSLog(@"%@",self.dataArray);
        }
        
        else if([self.totalDetails[@"page"] isEqualToString:@"2"])
        {
            
            NSMutableArray *tempArray = [NSMutableArray arrayWithArray:self.dataArray];
           
            //得到二级病类的模型数组
            
            NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            
            //得到二级病类的模型数组
            NSArray *array  = [NSArray yy_modelArrayWithClass:[CLDiseaseStyleModel class] json:response[@"data"]].copy;
            
            for (CLDiseaseStyleModel *object in array)
            {
                //如果病情名数组不包含 该 模型的病名 ，添加到数组数据里面
                if (![self.aryNames containsObject:object.ci3_name])
                {
                    [tempArray addObject:object];
                }
                
            }
            
            self.dataArray = tempArray.copy;
        }
        
        //从二级病类模型数组中提取 病类名数组
        NSMutableArray *arrayName = [NSMutableArray array];
        
        for (CLDiseaseStyleModel *obj in self.dataArray) {
            [arrayName addObject:obj.ci3_name];
        }
        
        self.aryNames = arrayName.copy;
        self.arySearchedNames = [NSMutableArray arrayWithArray:self.aryNames];
        NSLog(@"%@",self.aryNames);
        //刷新数据
        [self.tableView reloadData];
        // 结束更新刷新
        [self.tableView.mj_header endRefreshing];

        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [SVProgressHUD showImage:[UIImage imageNamed:@"warning"] status:@"网络加载失败"];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];//只有none是可以继续用户交互的
        // 结束刷新
        [self.tableView.mj_header endRefreshing];
        //延时
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });

        
    }];

}


#pragma mark - 数据源方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arySearchedNames.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid forIndexPath:indexPath];
    
    cell.textLabel.text = self.arySearchedNames[indexPath.row];
    
    cell.textLabel.textColor = [UIColor colorWithHex:0x666666];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    //去掉cell的颜色
    cell.backgroundColor = [UIColor clearColor];
    //设置有箭头
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

-(void)textChanged:(UITextField *)textField
{
    NSString *strText = textField.text;
    [self.arySearchedNames removeAllObjects];
    
    if (strText.length <= 0) {
        
        self.arySearchedNames = [NSMutableArray arrayWithArray:self.aryNames];
        [self.tableView reloadData];
        return;
    }
    
    [self.aryNames enumerateObjectsUsingBlock:^(NSString *strName, NSUInteger idx, BOOL *stop) {
        UTPinYinHelper *pinYinHelper = [UTPinYinHelper sharedPinYinHelper];
        if ([pinYinHelper isString:strName MatchsKey:strText IgnorCase:YES]) {
            [self.arySearchedNames addObject:strName];
        }
    }];
    
    [self.tableView reloadData];
}


#pragma mark - 代理方法
//被选中的时候 运行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //当先显示的cell数组中，模糊搜索后cell的内容
    NSString *string = self.arySearchedNames[indexPath.row];
    //给句被选cell还原到 总病情数组的 下标
    NSInteger i = [self.aryNames indexOfObject:string];
    
    //取对应的下标 返回模型
    self.returnModel = self.dataArray[i];
    
    // 这句话的意思 就是让table是否以动画的形式 取消indexPath这个位置的背景色
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.inputCompeletionBlock != nil) {
        self.inputCompeletionBlock(self.returnModel);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
    
}



#pragma mark - 懒加载

- (CLNetworkManager *)networkManager {
    
    if (_networkManager == nil) {
        
        _networkManager = [CLNetworkManager sharedManager];
        
            }
    return _networkManager;
    
    
}

-(NSArray *)dataArray
{
    if (_dataArray == nil) {
        
        _dataArray = [NSArray array];
        
    }
    return _dataArray;
}

-(NSArray *)aryNames
{
    if (_aryNames == nil) {
        
        _aryNames = [NSArray array];
        
    }
    return _aryNames;
}

-(NSMutableArray *)arySearchedNames
{
    if (_arySearchedNames == nil) {
        
        _arySearchedNames = [NSMutableArray array];
        
    }
    return _arySearchedNames;
}

#pragma mark - 取消系统线


- (void)viewDidLayoutSubviews
{ if([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
{ [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)]; }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])
    { [self.tableView setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)]; } }

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{ if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - 销毁
-(void)dealloc
{
    // controller 销毁的时候，取消所有正在下载的线程
    [self.networkManager cancelOperations];
    //销毁的时候 将page改为1
    [self.totalDetails setObject:@"1" forKey:@"page"];
    NSLog(@"我去了");
    
}

@end
